package com.emailsystem.emailsystem.service.impl;

import com.emailsystem.emailsystem.domain.Email;
import com.emailsystem.emailsystem.exception.MailException;
import com.emailsystem.emailsystem.exception.MailExceptionEnum;
import com.emailsystem.emailsystem.service.SmtpService;
import com.emailsystem.emailsystem.util.Impl.FileUtilImpl;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.Socket;

@Service
public class SMTPimpl implements SmtpService {
    public static  void sendServer(String string, BufferedReader in, PrintWriter out) throws IOException {
        out.println(string);
        System.out.println(in.readLine());
    }
    public static void sendServer(String string, PrintWriter out) {
        out.println(string);
    }

    public static void sendFile(String filepath, PrintWriter out) throws IOException {
        File attachment = new File(filepath); // 附件文件路径
        if(filepath.contains(".zip")) {
            sendServer("Content-Type: application/zip",out);
        }else if(filepath.contains(".doc")||filepath.contains(".docx")) {
            sendServer("Content-Type: application/msword",out);
        }else {
            sendServer("Content-Type: application/octet-stream",out);
        }
        sendServer("Content-Disposition: attachment; filename=\"" + attachment.getName() + "\"",out);
        sendServer("Content-Transfer-Encoding: base64",out);
        out.println();
        FileInputStream fis = new FileInputStream(attachment);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            out.print(new String(java.util.Base64.getEncoder().encode(buffer), "UTF-8"));
        }
        fis.close();
    }

    public static void sendImg(String filepath, PrintWriter out) throws IOException {
        File attachment = new File(filepath); // 附件文件路径
        sendServer("Content-Type: application/jpeg",out);
        sendServer("Content-Disposition: inline; filename=\"" + attachment.getName() + "\"",out);
        sendServer("Content-Transfer-Encoding: base64",out);
        out.println();
        FileInputStream fis = new FileInputStream(attachment);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            out.print(new String(java.util.Base64.getEncoder().encode(buffer), "UTF-8"));
        }
        fis.close();
    }

    @Override
    public  void  SMTPService(Email email, String serve, String password) {

        try {
            String host = serve; // QQ邮箱SMTP服务器地址
            int port = 25; // SMTP服务器端口号
            String username = email.getSender(); // 发送邮件的QQ邮箱账号
            String from = email.getSender(); // 发送人邮箱
            String to = email.getReceiver(); // 接收人邮箱
            String subject = email.getSubject(); // 邮件主题
            String body = email.getContent(); // 邮件正文

            // 建立连接
            Socket socket = new Socket(host, port);
            InputStream inputStream = socket.getInputStream();//读取服务器返回信息的流
            InputStreamReader isr = new InputStreamReader(inputStream);//字节解码为字符
            BufferedReader in = new BufferedReader(isr);//字符缓冲

            OutputStream outputStream = socket.getOutputStream();//向服务器发送相应信息
            PrintWriter out = new PrintWriter(outputStream, true);//true代表自带flush
            System.out.println(in.readLine());

            // 登录认证
            sendServer("HELO " + host,in,out);
            sendServer("AUTH LOGIN",in,out);
            sendServer(new String(java.util.Base64.getEncoder().encode(username.getBytes())),in,out);
            sendServer(new String(java.util.Base64.getEncoder().encode(password.getBytes())),in,out);

            // 发送邮件内容
            sendServer("MAIL FROM: <" + email.getSender() + ">",in,out);
            sendServer("RCPT TO: <" + email.getReceiver() + ">",in,out);
            sendServer("DATA",in,out);
           String mail= FileUtilImpl.MIME_Message_withAttachment(email);
           sendServer(mail,out);
//            sendServer("From: " + from,out);
//            sendServer("To: " + to,out);
//            sendServer("Subject: " + subject ,out);
//            sendServer("Content-Type: multipart/mixed; boundary=boundary1",out);
//            sendServer("--boundary1" ,out);
//            sendServer("Content-Type: multipart/related; boundary=boundary2",out);
//            sendServer("--boundary2",out);
//            sendServer("Content-Type: multipart/alternative; boundary=boundary3",out);
//            sendServer("--boundary3",out);
//            sendServer("Content-Type: text/plain;charset=UTF-8",out);
//            out.println();
//            sendServer(body,out);
//            out.println();
//            sendServer("--boundary3--",out);
//
//            if(email.getAttachmentPath().length!=0) {
//                for (int i = 0; i < email.getAttachmentPath().length; ++i) {
//                    sendServer("--boundary2", out);
//                    if (email.getAttachmentPath()[i].contains(".jpg")) {
//                        sendImg(email.getAttachmentPath()[i], out);
//                    }
//                    sendServer("--boundary2--", out);
//                }
//            } else{
//                sendServer("--boundary2",out);
//                sendServer("--boundary2--",out);
//            }
//            if(email.getAttachmentPath().length!=0)
//                for(int i=0;i<email.getAttachmentPath().length;++i)
//                {
//                    if(!email.getAttachmentPath()[i].contains(".jpg")) {
//                        sendServer("--boundary1", out);
//                        sendFile(email.getAttachmentPath()[i], out);
//                        sendServer("--boundary1--", out);
//                    }
//                }
//            else{
//                sendServer("--boundary1",out);
//                sendServer("--boundary1--",out);
//            }




            out.println();
            sendServer(".",in,out);

            // 关闭连接
            sendServer("QUIT",in,out);
            socket.close();
        }catch (IOException e){
            throw  new MailException(MailExceptionEnum.File_IO_EXCEPTION);
        }
    }
}

